<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" width="800px" append-to-body custom-class="import-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!--报修类型-->
        <el-form-item label="报修类型" key="maintenanceType" prop="maintenanceType">
          <el-select v-model="form.maintenanceType" placeholder="请选择报修类型" style="width: 100%;">
            <el-option
              v-for="dict in dict.type.maintenance_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <!--报修房源-->
        <el-form-item label="报修房源" key="houseId" prop="houseId" @click.stop="selectHouse">
          <el-input v-model="form.premisesAddress" placeholder="请选择报修房源" readonly @focus="selectHouse"
          ></el-input>
          <!--          <el-select v-model="form.houseId" placeholder="请选择报修房源" style="width: 100%;">-->
          <!--            <el-option v-for="(item,key) in repairHouseList" :key="key" :label="item.houseName" :value="item.id"></el-option>-->
          <!--          </el-select>-->
        </el-form-item>
        <el-form-item label="报修人" key="contactsName" prop="contactsName">
          <el-input v-model="form.contactsName" placeholder="请填写报修人"></el-input>
        </el-form-item>
        <!--    手机号    -->
        <el-form-item label="手机号" key="contactsPhone" prop="contactsPhone">
          <el-input v-model="form.contactsPhone" placeholder="请填写报修人手机号"></el-input>
        </el-form-item>
        <!--    维修项目    -->
        <el-form-item label="维修项目" key="repairProjectId" prop="repairProjectId">
          <el-select v-model="form.repairProjectId" placeholder="请选择维修项目" style="width: 100%;"
                     @change="getMaintenanceItemInfo" :disabled="form.houseId === ''"
          >
            <el-option v-for="item in projectList" :key="item.value" :label="item.label" :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--    备注信息    -->
        <el-form-item label="备注信息" key="workOrderRemark" prop="workOrderRemark">
          <el-input v-model="form.workOrderRemark" placeholder="请描述故障问题"></el-input>
        </el-form-item>
        <el-form-item label="预约时间" key="expectDateTime" required>
          <el-row :gutter="10">
            <el-col :span="10">
              <!--    期望上门时间    -->
              <el-form-item key="expectDate" prop="expectDate">
                <el-select v-model="form.expectDate" placeholder="请选择预约上门日期" style="width: 100%;">
                  <el-option :label="item.label" :value="item.value" v-for="(item,key) in sevenDays" :key="key"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <!--    期望上门时间    -->
              <el-form-item key="expectTime" prop="expectTime">
                <el-select v-model="form.expectTime" placeholder="请选择预约上门时间" style="width: 100%;" :disabled="!form.expectDate">
                  <el-option :label="item.value" :value="item.value" v-for="(item,key) in timeArr" :key="key" :disabled="item.disabled">{{ item.value }}</el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <!--    紧急程度    -->
        <el-form-item label="紧急程度" key="urgencyDegree" prop="urgencyDegree">
          <el-radio-group v-model="form.urgencyDegree">
            <el-radio label="1">普通</el-radio>
            <el-radio label="2">紧急</el-radio>
            <el-radio label="3">非常紧急</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--    故障照片    -->
        <el-form-item label="故障照片" key="faultPictureList" prop="faultPictureList">
          <ImageUpload v-model="form.faultPictureList" :limit="6" @change="handlePictureChange">
            <template slot="tip">
              * 仅支持图片格式（例如：jpg、png、jpeg等），最多上传6张每张最大5M；
            </template>
          </ImageUpload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
    <!-- 选择房间弹窗 -->
    <SelectRoom v-model="dialogSelectRoomVisible" @success="selectRoomSuccessCb" :selected-data="selectedList"/>
  </div>
</template>

<script>
import { debounce } from '@/utils'
import { addRoutineSweep } from '@/api/houseCleaning/sweep'
import { listLockModel, createLock } from '@/api/smartLock/lockManage'
import { compareDateTime, getDateName, getDateRange } from '@/utils/common/moment'
import { getMaintenanceItemInfo } from '@/api/houseManagement/maintenanceItem'
import SelectRoom from '@/views/components/select-room/index.vue'
import { addWorkOrder } from '@/api/houseManagement/workOrder'

export default {
  dicts: ['maintenance_type'],
  components: {
    SelectRoom

  },
  props: {
    title: {
      default: '添加报修'
    },
    value: {
      default: false
    },
    data: {
      default: undefined
    }
  },
  data() {
    return {
      form: {},
      rules: {
        maintenanceType: [
          { required: true, message: '请选择报修类型', trigger: ['blur', 'change'] }
        ],
        houseId: [
          { required: true, message: '请选择报修房源', trigger: ['blur', 'change'] }
        ],
        contactsName: [
          { required: true, message: '请填写报修人', trigger: ['blur', 'change'] }
        ],
        contactsPhone: [
          { required: true, message: '请填写报修人手机号', trigger: ['blur', 'change'] },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
        ],
        repairProjectId: [
          { required: true, message: '请选择维修项目', trigger: ['blur', 'change'] }
        ],
        expectDate: [
          { required: true, message: '请选择预约上门日期', trigger: ['blur', 'change'] }
        ],
        expectTime: [
          { required: true, message: '请选择预约上门时间', trigger: ['blur', 'change'] }
        ],
        urgencyDegree: [
          { required: true, message: '请选择紧急程度', trigger: ['blur', 'change'] }
        ],
        faultPictureList: [
          { required: false, message: '请上传故障照片', trigger: ['blur', 'change'] }
        ]
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      //列表
      list: [],
      // 维修员列表
      personList: [],
      // 房源列表
      repairHouseList: [],
      // 维修项目列表
      projectList: [],
      workOrderChargeItemList: [
        {
          itemId: null, //维修项目id
          itemName: '', //维修项目名
          materialCost: '', //材料费
          laborCost: '', //劳务费
          chargeQuantity: '' //收费数量(这里写死传1)
        }
      ],
      // 选择房间弹窗
      dialogSelectRoomVisible: false,
      //已选择列表
      selectedList: [],
      //收费项目参数
      workOrderChargeItemParams: {
        chargeItemType: '1', //收费项目类型(1.维修项目)(2.保洁项目),
        estateId: '', //房屋id
        tenantId: '' //企业id
      }
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    // 获取今天以及七天日期的对象数组
    sevenDays() {
      const today = new Date()    // 获取今天的日期对象
      // 获取七天后的日期对象
      const sevenDaysAfter = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000)
      const dateArr = getDateRange(today, sevenDaysAfter)
      let result = []
      for (let i = 0; i < dateArr.length; i++) {
        result.push({
          label: getDateName(dateArr[i]),
          value: dateArr[i]
        })
      }
      return result
    },
    // 获取时间段数组
    timeArr() {
      const arr = []
      for (let i = 6; i < 24; i++) {
        let time = i < 10 ? '0' + i + ':00' : i + ':00'
        let dateTime = this.form.expectDate + ' ' + time+':00'
        let item = {
          disabled: compareDateTime(new Date(), dateTime,'>'),
          value: time
        }
        arr.push(item)
      }
      return arr
    }
  },
  watch: {
    value: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.init()
        }
      },
      immediate: true
    }
  },
  methods: {
    init() {
      this.reset()
    },
    reset() {
      this.form = {
        workOrderType: '1', // 1.维修工单 2.保洁工单 3.看房工单
        maintenanceType: '1', //维修类型(1.个人维修,2.公共维修)
        houseId: '', //房屋id
        premisesAddress: '', //房屋地址
        contactsName: '', //报修人姓名
        contactsPhone: '', //报修人手机号
        workOrderRemark: '', //备注信息
        expectationStartTime: '', //期望上门开始时间
        expectationEndTime: '', //期望上门结束时间
        urgencyDegree: '1', //紧急程度(1.普通,2.紧急,3.非常紧急)
        faultPictureList: [], //故障照片集合
        workOrderChargeItemList: [],
        expectDate: '', //期望上门日期
        expectTime: '', //期望上门时间
        appointmentTime: '', //预约时间
        workOrderSource: '1' //工单来源(1.平台,2.B端小程序,3.C端小程序)
      }
      this.resetForm('form')
      this.selectedList = []
      // this.getProjectList()
    },
    //选择房间
    selectHouse() {
      this.dialogSelectRoomVisible = true
    },
    //选择房间回调
    selectRoomSuccessCb(data) {
      console.log('data', data)
      this.selectedList = data
      this.form.houseId = data[0].houseId
      this.form.premisesAddress = data[0].premisesAddress

      this.workOrderChargeItemParams.estateId = data[0].estateId
      this.workOrderChargeItemParams.tenantId = data[0].tenantId
      this.getProjectList()
    },
    // 获取维修项目列表
    getProjectList() {
      let params = { ...this.workOrderChargeItemParams }
      getMaintenanceItemInfo(params).then(response => {
        this.projectList = response.data.map(item => {
          return {
            ...item,
            label: item.maintenanceItemName,
            value: item.maintenanceItemId
          }
        })
      })
    },
    // 获取维修项目详情
    getMaintenanceItemInfo(value) {
      let data = this.projectList.find(item => item.value == value)
      console.log('data', data)
      this.form.workOrderChargeItemList = [
        {
          itemId: data.maintenanceItemId, //维修项目id
          itemName: data.maintenanceItemName, //维修项目名
          materialCost: data.materialCost, //材料费
          laborCost: data.laborCost, //劳务费
          chargeQuantity: 1 //收费数量(这里写死传1)
        }
      ]
    },
    // 上传图片处理
    handlePictureChange(fileList) {
      this.form.faultPictureList = fileList.map(item => item.url)
    },

    submitForm: debounce(function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.appointmentTime = this.form.expectDate + ' ' + this.form.expectTime + ':00'
          // 上传图片处理
          console.log('form', this.form)
          addWorkOrder(this.form).then(response => {
            if (response.code == 200) {
              this.$emit('success')
              this.$message.success('添加成功')
              this.visible = false
            } else {
              this.$message.error(response.msg)
            }
          })
        }
      })
    }, 500, false),
    cancel() {
      this.reset()
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/dialog";
</style>
